from ckeditor_uploader.views import ImageUploadView
from django.conf import settings
from django.http import HttpResponse, JsonResponse
from django.utils.html import escape

from ckeditor_uploader import image_processing, utils


class MyImageUploadView(ImageUploadView):

    def post(self, request, **kwargs):
        """
        Uploads a file and send back its URL to CKEditor.
        继承ImageUploadView,重写post的方法
        解决(str(saved_path).split('.')[1]无后缀名的问题
        """
        uploaded_file = request.FILES['upload']

        backend = image_processing.get_backend()

        ck_func_num = request.GET.get('CKEditorFuncNum')
        if ck_func_num:
            ck_func_num = escape(ck_func_num)

        # Throws an error when an non-image file are uploaded.
        if not getattr(settings, 'CKEDITOR_ALLOW_NONIMAGE_FILES', True):
            try:
                backend.image_verify(uploaded_file)
            except utils.NotAnImageException:
                return HttpResponse("""
                    <script type='text/javascript'>
                    window.parent.CKEDITOR.tools.callFunction({0}, '', 'Invalid file type.');
                    </script>""".format(ck_func_num))

        saved_path = self._save_file(request, uploaded_file)
        # if(str(saved_path).split('.')[1].lower() != 'gif'): ----- 解决(str(saved_path).split('.')[1]无后缀名的问题
        if (str(saved_path).lower() != 'gif'):
            self._create_thumbnail_if_needed(backend, saved_path)
        url = utils.get_media_url(saved_path)

        if ck_func_num:
            # Respond with Javascript sending ckeditor upload url.
            return HttpResponse("""
            <script type='text/javascript'>
                window.parent.CKEDITOR.tools.callFunction({0}, '{1}');
            </script>""".format(ck_func_num, url))
        else:
            retdata = {'url': url, 'uploaded': '1',
                       'fileName': uploaded_file.name}
            return JsonResponse(retdata)
